/**
    @project {
        "templateId": "org.helgoboss.custom",
        "version": "0.1-SNAPSHOT",
        "dependencies": [
            "org.scala-lang:scala-library:2.9.0-1",
            "org.helgoboss:osgi-additions:0.1-SNAPSHOT",
            "org.osgi:org.osgi.compendium:4.2.0"
        ]
    }
*/

package org.helgoboss.system_property_configuration_plugin

import org.helgoboss.osgi_additions._
import org.osgi.service.cm._
import org.osgi.framework.ServiceReference
import java.util.Dictionary

class Activator extends OsgiContext with OsgiProvider with OsgiLogging {
    whenBundleActive {
        new ConfigurationPlugin {
            def modifyConfiguration(ref: ServiceReference, properties: Dictionary[_, _]) {
                log.info("Modifying config")
                val typedProperties = properties.asInstanceOf[Dictionary[String, AnyRef]]
                import collection.JavaConversions.dictionaryAsScalaMap
                typedProperties.toMap.foreach { case (key, value) =>
                    System.getProperties.foreach { case (sysKey, sysValue) =>
                        val newValue = value.toString.replaceAll("""#\{""" + sysKey + """\}""", sysValue.toString)
                        if (newValue != value) {
                            typedProperties.put(key, newValue)
                        }
                    }
                }
            }
        }.providesService[ConfigurationPlugin]
    }
}